<template>
  <el-dialog :visible="isPop" title="自定义字段" width="1000px" @close="onClose" append-to-body class="addItemPop" @open="onOpen">
    <el-form :model="form" ref="form" label-width="auto" inline label-suffix="：" :rules="rules">
      <el-form-item label="项目分类">
        <el-input v-model="title" disabled />
      </el-form-item>
      <el-form-item label="项目名称" prop="name">
        <el-input v-model="form.name" :disabled="!!row && !tem" />
      </el-form-item>
      <el-form-item label="计算规则">
        <el-radio-group v-model="form.salaryRule">
          <el-radio v-for="item in getRules" :key="item.id" :label="item.value">
            {{ item.label }}
            <span class="formula" v-if="form.salaryRule == 6 && item.value == 6" @click="onFormula">规则：{{ form.formulaShow || "未配置" }}</span>
            <standard-formula ref="standardFormula" v-if="form.salaryRule == 11 && item.value == 11" :item="JSON.parse(JSON.stringify({ title, ...form }))" />
          </el-radio>
        </el-radio-group>
        <!-- 花名册 -->
        <!-- <el-select v-model="roster" v-if="form.salaryRule == 1">
          <el-option v-for="item in rosterArr" :key="item.id" :value="item.value" :label="item.label" />
        </el-select> -->
        <!-- 自定义公式 -->
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" @click="onAffirm" :loading="loading">确认</el-button>
    </template>
    <el-dialog :visible="isFormulaPop" title="自定义公式" :close-on-click-modal="false" @open="onFormulaOpen" @opened="onFormulaOpened" @close="onFormulaClose" append-to-body width="1300px" class="formulaPop">
      <custom-formula ref="formula" :title.sync="row.name" @callbackLoading="callbackLoading">
        <slot v-bind:loading="customLoading">
          <el-button @click="isFormulaPop = false">取消</el-button>
          <el-button type="primary" @click="onFormulaAffirm" :loading="customLoading">确认</el-button>
        </slot>
      </custom-formula>
    </el-dialog>
  </el-dialog>
</template>
<script>
import { convertWord, getStandardFormula } from "@/util/xc/utils";
import { mapState } from "vuex";
import CustomFormula from "../../../CustomFormula/CustomFormula.vue";
import standardFormula from "./standardFormula/standardFormula.vue";
import { checkRE } from "../../utils";

export default {
  name: "addItemPop",
  components: { CustomFormula, standardFormula },
  props: {
    isPop: {
      type: Boolean,
      default: false
    },
    group: [Object, String], //  type 1:花名册; 2:薪酬档案; 3:自定义公式
    row: [Object, String],
    tem: {
      // true :  模板修改
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      isFormulaPop: false,
      title: "",
      form: {
        name: "",
        salaryRule: 4
      },
      initObj: {
        salaryRule: 4,
        name: "",
        isCustom: true,
        salaryColumnVisible: true,
        isVisible: true,
        formulaShow: null
      },
      rules: {
        name: {
          required: true,
          message: "请输入项目名称",
          validator: (rule, value, callback) => {
            if (!value) {
              rule.message = "请输入项目名称";
              return callback(new Error());
            } else if (!isNaN(Number(value))) {
              rule.message = "请输入正确的项目名称";
              return callback(new Error());
            } else if (checkRE(value)) {
              rule.message = "禁止输入特殊字符";
              return callback(new Error());
            } else callback();
          }
        }
      },
      rosterArr: [
        { id: 1, value: "name", label: "姓名" },
        { id: 2, value: "age", label: "年龄" }
      ],
      roster: "",
      radioArr: [
        { id: 4, value: 4, label: "手工导入" },
        { id: 1, value: 1, label: "从人员花名册处获取" },
        { id: 2, value: 2, label: "大类公式" },
        { id: 3, value: 3, label: "薪酬档案处获取" },
        { id: 5, value: 5, label: "考勤计薪规则获取" },
        { id: 6, value: 6, label: "自定义公式" },
        { id: 7, value: 7, label: "社保公积金处获取" },
        { id: 8, value: 8, label: "薪酬字段获取" },
        { id: 11, value: 11, label: "系统公式" }
        // { id: 10, value: 10, label: "自定义逻辑公式" },
      ],
      type: 3, // 1:花名册, 2:薪酬, 3:自定义公式
      customLoading: false
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.common.userInfo,
      standardFormula: state => state.reward.standardFormula
    }),

    /** 是否有标准公式 */
    isSystem() {
      const bol = this.title == "请假扣款" ? true : this.standardFormula.some(item => item.columnPy == this.form.namePy);
      return bol;
    },
    getRules() {
      const type = this.type - 1;
      const arr = [
        [4, 1],
        [4, 3],
        [4, 7],
        [4, 6]
      ];
      return this.radioArr.filter(item => arr[type].includes(item.value) || this.isSystem && item.value == 11);
    }
  },
  methods: {
    onOpen() {
      this.$nextTick(this.$refs.form?.clearValidate);
      if (this.row) {
        // 编辑
        this.$set(this, "form", JSON.parse(JSON.stringify(this.row)));
        if (this.form.salaryRule == 10) this.form.salaryRule = 6;
      } else {
        // 新增
        this.form = { ...this.initObj };
      }
      this.title = this.group.name;
      this.setType(this.title);

      this.$refs?.formula?.getData();
    },
    setType(title) {
      const arr = [[], ["个人信息"], ["基础工资"], ["个人社保公积金"]];
      const i = arr.findIndex(item => item.includes(title));
      this.type = i < 0 ? 4 : i;
      console.log(this.type, title);
    },
    onClose() {
      this.$refs?.formula?.clearContent();
      this.$emit("update:isPop", false);
      setTimeout(() => {
        this.form.salaryRule = 4;
      }, 500);
    },
    // 确认相关
    ...{
      async onAffirm() {
        try {
          this.loading = true;
          if (this.form.salaryRule == 11) await this.$refs?.standardFormula?.[0]?.setParams();
          await this.verify();
          const data = this.row ? await this.editColumn() : await this.addColumn();
          this.onClose();
          this.$emit("affirm", {
            edit: !!this.row,
            data: JSON.parse(JSON.stringify({ ...data, isVisible: this.tem ? data.isVisible : this.initObj.isVisible }))
          });
        } catch (message) {
          if (typeof message === "string" && message) this.$message({ message, type: "warning" });
        } finally {
          this.loading = false;
        }
      },
      verify() {
        return new Promise((resolve, reject) => {
          this.$refs.form.validate(valid => {
            if (valid) {
              if (this.form.salaryRule == 6 && !this.form.formulaShow) reject("请先配置自定义公式");
              else resolve();
            } else reject();
          });
        });
      },
      handleData(isEdit) {
        const { name, salaryRule, isCustom, salaryColumnVisible, beforeAfterTax = "税前", formulaDetail, formulaShow = null } = this.form;
        let data = {
          salaryRule: salaryRule == 6 ? this.salaryRule : salaryRule,
          name,
          namePy: convertWord(name),
          isCustom,
          salaryColumnVisible,
          beforeAfterTax,
          formulaShow: salaryRule == 6 ? formulaShow : null,
          itemId: this.group.id,
          formulaSummary: this.getDescribe(salaryRule),
          companyId: this.userInfo.CompanyId,
          formulaDetail: salaryRule == 6 ? formulaDetail : null
        };
        let edit = {};
        if (isEdit) {
          const { id, subId, salaryItemId, salaryTId, holidayTypeId } = this.form;
          if (this.tem) {
            edit = { id, holidayTypeId };
          } else {
            edit = { id, subId, salaryItemId, formulaDetail, salaryTId, holidayTypeId };
            delete data.itemId;
          }
        }
        return { ...edit, ...data };
      },
      async addColumn() {
        const params = this.handleData();
        console.log(params);
        // return Promise.reject();
        const { data, message = "添加成功" } = await this.$api.smartSalary.addColumn(params).then(res => res.data);
        this.$message({ message, type: "success" });
        return data;
      },
      async editColumn() {
        const params = this.handleData(true);
        if (this.tem) {
          console.log(params);
          // return Promise.reject();
          // 模板编辑
          const { data, message = "编辑成功" } = await this.$api.smartSalary.editSalaryColumnTemplate(params).then(res => res.data);
          this.$message({ message, type: "success" });
          console.log(data, message);
        }
        return params;
      },
      getDescribe(rule) {
        if (rule == 6) return this.form.formulaShow;
        const o = this.radioArr.find(item => item.value == rule);
        return o?.alias || o?.label || "";
      }
    },
    // 规则相关
    ...{

      /** 自定义公式 */
      onFormula() {
        this.isFormulaPop = true;
      }
    },
    // 自定义公式
    ...{
      callbackLoading(bol = false) {
        this.customLoading = bol;
      },
      onFormulaOpen() {},
      onFormulaOpened() {
        this.$refs?.formula?.callback(this.form.formulaShow);
        // this.$refs?.formula?.keyboardMonitoring();
      },
      onFormulaClose() {
        this.isFormulaPop = false;
        document.onkeydown = undefined;
      },
      async onFormulaAffirm() {
        const formula = await this.$refs?.formula?.checkFormula(true);
        if (formula) {
          const { equation, equation_name, salaryRule } = formula;
          console.log("确认", formula);
          this.form.formulaShow = equation_name;
          this.form.formulaDetail = equation;
          this.salaryRule = salaryRule;
          this.isFormulaPop = false;
        }
      }
    }
  },
  mounted() {
    getStandardFormula();
  }
};
</script>
<style lang="less" scoped>
.formulaPop {
  display: flex;
  justify-content: center;
  align-items: center;
  :deep( .el-dialog) {
    height: 90%;
    display: flex;
    margin: 0 !important;
    flex-direction: column;
    .el-dialog__body {
      flex: 1;
      overflow: hidden;
      #Formula {
        height: 100%;
      }
    }
  }
}
.addItemPop {
  :deep( .el-dialog__body) {
    .el-form {
      display: flex;
      flex-direction: column;
      .el-form-item {
        display: flex;
        .el-form-item__label {
          white-space: nowrap;
        }
        .el-form-item__content {
          & > .el-radio-group {
            display: flex;
            flex-direction: column;
            .el-radio {
              margin: 10px 0;
            }
          }
        }
      }
    }
    .formula {
      display: block;
      margin: 20px 30px 10px;
      width: 200px;
      color: #666;
      margin-left: 30px;
      font-size: 12px;
      cursor: pointer;
    }
  }
}
</style>
